package com.ych.DemoSSM.common.util;

import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.log4j.Logger;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class Mail {

    private static Logger logger = Logger.getLogger(Mail.class);

    public static Session getSession(String smtp, final String sendUser, final String sendPasswd) {
        Session session;
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", smtp);
        props.setProperty("mail.smtp.port", "465");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            logger.info("ssl 启用失败");
        }
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sendUser, sendPasswd);
            }
        });
        session.setDebug(true);
        return session;
    }

    public static boolean send(Session session, String sender, String[] receivers, String title, String content) {
        try {
            MimeMessage message = new MimeMessage(session);
            InternetAddress from = new InternetAddress(sender);
            message.addRecipient(Message.RecipientType.CC, from);
            message.setFrom(from);
            for (String receiver : receivers) {
                InternetAddress to = new InternetAddress(receiver);
                message.addRecipient(Message.RecipientType.TO, to);
            }
            message.setSubject(title);
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(content, "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            message.setContent(mainPart);
            Transport.send(message);
            logger.info("邮件发送成功");
            return true;
        } catch (Exception e) {
            logger.error("邮件发送失败", e);
            return false;
        }
    }

    public static void main(String[] args) {
        String[] receivers = new String[]{"lbyqc@163.com"};
        Session session = getSession("smtp.qq.com", "3218590394@qq.com", "blmwtysntowydhfd");
        send(session, "3218590394@qq.com", receivers,
                "[提醒]邮件提醒", "截止目前开源中国收录了 44517 款开源项目，囊括了最热门的各类开源项目");
    }
}
